<template>
    <div>
        <page-header title="文章管理">
            <template #content>
              <p>文章管理</p>
            </template>
        </page-header>

        <page-main>
            <el-row style="margin-bottom: 24px;">
                <el-button type="primary" @click="openDialog">发起审批</el-button>
            </el-row>
            <el-row :gutter="24">
                <el-col :span="12">
                    我发起的审批
                    <el-table :data="dataCreateByMe" border stripe highlight-current-row>
                        <el-table-column prop="createdAt" label="发起时间"></el-table-column>
                        <el-table-column prop="name" label="审批名称"></el-table-column>
                        <el-table-column prop="createdBy" label="发起人"></el-table-column>
                        <el-table-column prop="approvalStatus" label="审批状态">
                            <template #default="scope">
                                <span v-if="scope.row.approvalStatus == 'UNDER_APPROVAL'">审批中</span>
                                <span v-if="scope.row.approvalStatus == 'PENDING_APPROVAL'">待审批</span>
                                <span v-if="scope.row.approvalStatus == 'APPROVED'">通过</span>
                                <span v-if="scope.row.approvalStatus == 'REJECTED'">驳回</span>
                                <span v-if="scope.row.approvalStatus == 'NOT_APPROVED'">待审批</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="85">
                            <template #default="scope">
                                <el-button type="primary" size="text" @click="checkDialog(scope.row)">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
                <el-col :span="12" v-if="isTrue">
                    我的审批记录
                    <el-table :data="dataApprovedByMe" border stripe highlight-current-row>
                        <el-table-column prop="createdAt" label="发起时间"></el-table-column>
                        <el-table-column prop="name" label="审批名称"></el-table-column>
                        <el-table-column prop="createdBy" label="发起人"></el-table-column>
                        <el-table-column prop="approvalStatus" label="审批状态">
                            <template #default="scope">
                                <span v-if="scope.row.approvalStatus == 'UNDER_APPROVAL'">审批中</span>
                                <span v-if="scope.row.approvalStatus == 'PENDING_APPROVAL'">待审批</span>
                                <span v-if="scope.row.approvalStatus == 'APPROVED'">通过</span>
                                <span v-if="scope.row.approvalStatus == 'REJECTED'">驳回</span>
                                <span v-if="scope.row.approvalStatus == 'NOT_APPROVED'">待审批</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="85">
                            <template #default="scope">
                                <el-button type="primary" size="text" @click="handleDialog(scope.row)">查看详情</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>
            </el-row>
        </page-main>
        <el-dialog
            v-model="dialogVisible"
            :title="dialogTitle"
            :close-on-click-modal="false"
            width="35%"
        >
            <el-row>
                <el-col>
                    <el-form ref="formRef" :model="form" :rules="rules" label-width="120">
                        <el-form-item label="名称：" prop="name">
                            <el-input v-if="dialogTitle == '发起审批'" v-model="form.name" placeholder="请输入名称"></el-input>
                            <span v-else>{{ form.name }}</span>
                        </el-form-item>
                        <el-form-item label="选择文章：" prop="fileId">
                            <el-tree-select
                            v-if="dialogTitle == '发起审批'"
                            v-model="form.fileId"
                            :data="treeList"
                            node-key="id"
                            :props="defaultProps"
                            :load="loadNode"
                            lazy></el-tree-select>
                            <span v-else>
                                <span>{{ form.fileName }}</span>
                                &nbsp;&nbsp;
                                <el-button :icon="Download" size="small" @click="downloadFile()">查看</el-button>
                            </span>
                        </el-form-item>
                        <el-form-item label="审批状态：" v-if="dialogTitle == '我发起的审批'">
                            <span v-if="form.approvalStatus == 'UNDER_APPROVAL'">审批中</span>
                            <span v-if="form.approvalStatus == 'PENDING_APPROVAL'">待审批</span>
                            <span v-if="form.approvalStatus == 'APPROVED'">通过</span>
                            <span v-if="form.approvalStatus == 'REJECTED'">驳回</span>
                            <span v-if="form.approvalStatus == 'NOT_APPROVED'">待审批</span>
                        </el-form-item>
                        <el-form-item label="审批：" v-if="dialogTitle == '处理审批' && form.approvalStatus == 'PENDING_APPROVAL'">
                            <div>
                                <div class="addApp" @click="handleApproval(true)">通过</div>
                                <div class="addApp" @click="handleApproval(false)">驳回</div> 
                            </div>
                        </el-form-item>
                        <el-form-item label="备注：" prop="remark" v-if="dialogTitle == '处理审批' && form.approvalStatus == 'PENDING_APPROVAL'">
                            <el-input v-model="form.remark" placeholder="备注"></el-input>
                        </el-form-item>
                        <el-form-item label="审批流程：" prop="approvalUsers">
                            <div>
                                <div v-for="(item, index) in form.approvalUsers" style="text-align: center;" v-if="dialogTitle == '发起审批'">
                                    <div class="addApp">
                                        {{ item.name }}
                                        <font class="appFont" @click="deleteAppUser(index)">移除</font>
                                    </div>
                                    <el-icon color="#000"><Bottom /></el-icon>
                                </div>
                                <div v-for="(item, index) in form.approvalUsers" style="text-align: center;" v-else>
                                    <div class="addApp">
                                        {{ item.approvalUserName }}
                                        :
                                        <span v-if="item.approvalStatus == 'UNDER_APPROVAL'">审批中</span>
                                        <span v-if="item.approvalStatus == 'PENDING_APPROVAL'">待审批</span>
                                        <span v-if="item.approvalStatus == 'APPROVED'">通过</span>
                                        <span v-if="item.approvalStatus == 'REJECTED'">驳回</span>
                                        <span v-if="item.approvalStatus == 'NOT_APPROVED'">待审批</span>
                                        <br v-if="item.approvalAt">
                                        {{ item.approvalAt }}
                                        <br v-if="item.remark">
                                        {{ item.remark }}
                                    </div>
                                    <el-icon v-if="index != form.approvalUsers.length - 1" color="#000"><Bottom /></el-icon>
                                </div>
                                <div class="addApp" v-if="dialogTitle == '发起审批'">
                                    <span v-if="!addVisible" @click="addVisible = true;  addUserVal = ''">添加审批人</span>
                                    <el-tree-select
                                    v-model="addUserVal"
                                    :data="userList"
                                    :props="defaultProps"
                                    node-key="id"
                                    v-else
                                    @change="changeAddUser">
                                    </el-tree-select>
                                </div>
                            </div>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
            <template #footer>
                <span class="dialog-footer">
                    <el-button type="primary" @click="submitAdd" v-if="dialogTitle == '发起审批'">确定</el-button>
                    <el-button @click="dialogVisible = false">取消</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="editor">
            <v-md-preview :text="editorText" height="400px" width="100%"></v-md-preview>
        </el-dialog>
    </div>
</template>

<script setup>
// 查询审批记录 approvalGet(params)
// 创建审批 approvalCreate(data)
// 审批 approvalTake(id, data)
import useFileStore from '@/store/modules/file';
import { Bottom } from "@element-plus/icons-vue";
import useUserStore from '@/store/modules/user'
import moment from "moment"
import { Download } from '@element-plus/icons-vue'

const fileStore = useFileStore();
const userStore = useUserStore()

const userList = ref([]);
const treeList = ref([]);
const defaultProps = ref({
    children: 'children',
    label: 'name',
    isLeaf: 'file'
});
const isTrue = ref(localStorage.getItem("MEDIA_USER_INFO") && (JSON.parse(localStorage.getItem("MEDIA_USER_INFO")).role == 'ADMIN'));
const dataCreateByMe = ref([]);
const dataApprovedByMe = ref([]);
const dialogVisible = ref(false);
const editor = ref(false);
const editorText = ref("");
const dialogTitle = ref("");
const addVisible = ref(false);
const addUserVal = ref("");
const formRef = ref(null);
const form = ref({
    name: "",
    fileId: "",
    approvalUserIds: [],
    approvalUsers: [],
    remark: ""
});
const rules = ref({
    name: [
        { required: true, message: "请输入名称", trigger: 'blue' }
    ],
    fileId: [
        { required: true, message: "请选择审批文章", trigger: 'blue' }
    ],
    approvalUsers: [
        { required: true, message: "请选择审批人员", trigger: 'blue' }
    ]
});

onMounted(() => {
    getList()
    const params = {
        page: 0,
        size: 100,
    }
    userStore.getAccoutTree(params).then(res => {
        userList.value = res
    })
})

function getList() {
    fileStore.approvalGet({createByMe: true}).then(res => {
        res.forEach(item => {
            item.createdAt = moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss")
            item.approvalNodes.forEach(item => {
                if(!!item.approvalAt)
                item.approvalAt = moment(item.approvalAt).format("YYYY-MM-DD HH:mm:ss")
            })
        })
        dataCreateByMe.value = res
    })
    fileStore.approvalGet({approvedByMe: true}).then(res => {
        res.forEach(item => {
            item.createdAt = moment(item.createdAt).format("YYYY-MM-DD HH:mm:ss")
            item.approvalNodes.forEach(item => {
                if(!!item.approvalAt)
                item.approvalAt = moment(item.approvalAt).format("YYYY-MM-DD HH:mm:ss")
            })
        })
        dataApprovedByMe.value = res
    })
}

function openDialog() {
    dialogVisible.value = true
    form.value = { name: "", fileId: "", approvalUsers: [], approvalUserIds: [] }
    // if(dataCreateByMe.value.length) {
    //     dataCreateByMe.value[0].approvalNodes.forEach(item => {
    //         form.value.approvalUsers.push({name: item.approvalUserName, userId: item.id})
    //     })        
    // }
    treeList.value = []
    dialogTitle.value = "发起审批"
    fileStore.getPersonalFileList().then(res => {
        treeList.value.push(res)
    })
    fileStore.getPublicFileList().then(res => {
        treeList.value.push(res)
    })
}

function downloadFile() {
    fileStore.filePath(form.value.filePath).then(res => {
        editorText.value = res
        editor.value = true
    })
}

function checkDialog(val) {
    dialogVisible.value = true
    dialogTitle.value = '我发起的审批'
    form.value.name = val.name
    form.value.filePath = val.filePath
    form.value.fileName = val.filePath.split("_")[1]
    form.value.approvalUsers = val.approvalNodes
    form.value.approvalStatus = val.approvalStatus
}

function handleDialog(val) {
    dialogVisible.value = true
    dialogTitle.value = '处理审批'
    form.value.remark = ""
    form.value.name = val.name
    form.value.filePath = val.filePath
    form.value.fileName = val.filePath.split("_")[1]
    form.value.approvalUsers = val.approvalNodes
    form.value.approvalStatus = val.approvalStatus
    val.approvalNodes.forEach(item => {
        if(item.approvalStatus == 'PENDING_APPROVAL') {
            form.value.chosenVal = item
        }
    })
}

function handleApproval(val) {
    ElMessageBox.confirm('确定通过审批吗？', '提示',  {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
    }).then(() => {
        let obj = {
            approvalStatus: val ? "APPROVED" : "REJECTED",
            remark: form.value.remark
        }
        fileStore.approvalTake(form.value.chosenVal.id, obj).then(res => {
            ElMessage({
                type: "success",
                message: "操作成功"
            })
            dialogVisible.value = false
            getList()
        })
    }).catch(() => {})
}

function submitAdd() {
    formRef.value.validate(valid => {
        if(valid) {
            let obj = {
                name: form.value.name,
                fileId: form.value.fileId,
                approvalUserIds: []
            }
            form.value.approvalUsers.forEach(item => {
                obj.approvalUserIds.push(item.userId)
            })
            fileStore.approvalCreate(obj).then(res => {
                ElMessage({
                    type: "success",
                    message: "操作成功"
                })
                getList()
                dialogVisible.value = false
            })
        }
    })
}

function changeAddUser(val) {
    addVisible.value = false
    handleSearch(val, userList.value)
}

function handleSearch(val, obj) {
    obj.forEach(item => {
        if(item.id == val) {
            form.value.approvalUsers.push(item)
        }
        if(item.children && item.children.length) {
            handleSearch(val, item.children)
        }
    })
}

function deleteAppUser(i) {
    form.value.approvalUsers.splice(i, 1)
}

function loadNode(node, resolve) {
    if(node.data.children && node.data.children.length) {
        resolve(node.data.children)
    } else if(node.data.id) {
        fileStore.getFileList(node.data.id).then(res => {
            return resolve(res.children)
        })
    }
}
</script>

<style scoped>
.addApp {
    padding: 5px 10px;
    margin-top: 5px;
    text-align: center;
    color: #000;
    font-size: 16px;
    background-color: rgba(90, 196, 246, 0.75);
    cursor: pointer;
    width: 250px;
}
.appFont {
    color: #102eff;
    font-size: 12px;
}
</style>
